﻿using OF.Component.BLL;
using OF.Component.Model;
using Msg.Api.Controllers;
using OF.Utility.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using OF.Utility;

namespace Msg.Api.Filters
{
    /// <summary>
    /// 异常处理
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class APIExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 重写异常处理
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)
            {
                //api2的错误,屏蔽
                if (actionExecutedContext.Exception.Message.StartsWith("已取消该操作"))
                {
                    return;
                }

                var actionContext = actionExecutedContext.ActionContext;

                //记录错误日志
                ErrorLog log = new ErrorLog();
                log.APPVersion = GetHeaderValue(actionContext, "appversion");
                log.ClientId = GetHeaderValue(actionContext, "appclientid");
                log.Imei = GetHeaderValue(actionContext, "appimei");
                log.Moble = GetHeaderValue(actionContext, "appmobile");
                log.Model = GetHeaderValue(actionContext, "appmodel");
                log.PlatformID = int.Parse(SiteUtility.GetAppSettings("LogPlatformID"));
                log.PlatformVersion = GetHeaderValue(actionContext, "apposversion");
                log.Token = GetHeaderValue(actionContext, "apptoken");
                if (HttpContext.Current != null)
                {
                    log.UA = HttpContext.Current.Request.UserAgent;
                }
                log.Uuid = GetHeaderValue(actionContext, "appuuid");
                log.Vendor = GetHeaderValue(actionContext, "appvendor");
                log.RequestMethod = actionContext.Request.Method.Method;
                if (log.RequestMethod.Equals("POST", StringComparison.Ordinal))
                {
                    log.PostData = GetPostData(actionContext);
                }
                log.RequestUrl = actionContext.Request.RequestUri.AbsoluteUri;
                log.ClientIP = HttpContextHelper.GetIpaddress();
                log.ErrorSource = actionExecutedContext.Exception.Source;
                log.ErrorMessage = actionExecutedContext.Exception.Message;
                log.ErrorTrace = actionExecutedContext.Exception.StackTrace;
                log.CreatedDate = DateTime.Now;
                
                try
                {
                    ErrorLogHelper.Error(log);
                }
                catch (Exception ex)
                {
                    ErrorLogHelper.Error(ex);
                }

                //如果截获异常是我没无法预料的异常，则将通用的返回信息返回给用户，避免泄露过多信息，也便于用户处理
                //actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, "抱歉，系统出了点小问题，请稍后再试!");
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, actionExecutedContext.Exception.Message);
            }

        }

        /// <summary>
        /// 获取制定的header值
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetHeaderValue(HttpActionContext actionContext, string name)
        {
            IEnumerable<string> headers;
            if (actionContext.Request.Headers.TryGetValues(name, out headers))
            {
                return headers.FirstOrDefault();

            }
            return "";
        }

        /// <summary>
        /// 获取post数据
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected string GetPostData(HttpActionContext actionContext)
        {
            string str = "";
            if (actionContext.Request.Content.IsMimeMultipartContent())
            {
                return "";
            }
            try
            {
                if (actionContext.Request.Content.IsFormData())
                {
                    NameValueCollection nv = actionContext.Request.Content.ReadAsFormDataAsync().Result;
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in nv.AllKeys)
                    {
                        sb.AppendFormat("key:{0},value:{1},", item, nv[item]);
                    }
                    str = sb.ToString();
                }
                else
                {
                    Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
                    if (stream != null && stream.Length > 0)
                    {
                        stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
                        using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
                        {
                            str = reader.ReadToEnd().ToString();
                        }
                    }
                }

            }
            catch (Exception ex) {
                Log4netLog.Debug(ex.Message);
            }
            return str;
        }
    }
}